package com.danbay.cloud.account.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.danbay.cloud.account.entity.*;
import com.danbay.cloud.account.mapper.*;
import com.danbay.cloud.base.constants.Const;
import com.danbay.cloud.base.constants.Roles;
import com.danbay.cloud.base.user.LoginUserInfo;
import com.danbay.framework.exception.BusinessException;
import com.danbay.framework.redis.RedisClient;
import com.danbay.framework.utils.BeanUtils;
import com.danbay.framework.utils.CollectionUtils;
import com.danbay.framework.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author SJG
 *         2018/1/11.
 */
@Service
public class LoginUserService {
    @Autowired
    private PermissionGroupMapper permissionGroupMapper;
    @Autowired
    private AccountPermissionMapper accountPermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MyPermissionMapper myPermissionMapper;
    @Autowired
    private EnterpriseMapper enterpriseMapper;
    @Autowired
    private AccountRoleMapper accountRoleMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisClient redisClient;


    /**
     * 取已登录了的用户信息
     *
     * @param userName 账号
     * @return 用户信息
     */
    public LoginUserInfo getLoginUserInfo(String userName) {
        return redisClient.getEntity(Const.LOGIN_USER_INFO + userName);
    }

    /**
     * 更新缓存的用户登录信息
     *
     * @param userInfo 用户登录信息
     */
    public void updateCachedLoginUserInfo(LoginUserInfo userInfo) {
        redisClient.setEntity(userInfo.getUserName(), userInfo);
    }

    /**
     * 缓存登录用户信息
     *
     * @param account 账号
     * @param groupId 账户组id
     * @param role    角色
     */
    public LoginUserInfo cacheLoginUserInfo(Account account, Integer groupId, String role) {
        //查出拥有的权限
        List<AccountPermission> accountPermissions = accountPermissionMapper.selectList(
                new EntityWrapper<>(AccountPermission.builder()
                        .userName(account.getUserName())
                        .accountGroupId(groupId).build()));
        //取所有权限组
        List<PermissionGroup> allPermissionGroups = permissionGroupMapper.selectList(new EntityWrapper<>(new PermissionGroup()));
        StringBuilder sbAllPid = new StringBuilder();
        StringBuilder sbExcludePid = new StringBuilder();
        for (AccountPermission ap : accountPermissions) {
            sbExcludePid.append(ap.getExcludePermissions()).append(",");
            for (PermissionGroup pg : allPermissionGroups) {
                if (ap.getPermissionGroupId() == pg.getId().intValue()) {
                    sbAllPid.append(pg.getPermissionIds()).append(",");
                }
            }
        }

        String allExcludePid = sbExcludePid.toString();
        //从权限id中过滤要排除的id
        List<String> myPermissionIds = new ArrayList<>();
        myPermissionIds.addAll(Arrays.asList(sbAllPid.toString().split(",")));
        CollectionUtils.filter(myPermissionIds, s ->
                !allExcludePid.contains(s + ",")
        );
        //查取当前用户所有的权限信息
        List<Permission> myPermissions = permissionMapper.selectBatchIds(myPermissionIds);
        //同步权限到我的权限表
        //先删除原有的
        myPermissionMapper.delete(new EntityWrapper<>(MyPermission.builder().userName(account.getUserName()).build()));
        //再添加  todo 需要优化成批量插入
        for (Permission p : myPermissions) {
            myPermissionMapper.insert(MyPermission.builder().userName(account.getUserName()).permissionId(p.getId()).build());
        }

        //同步权限到缓存
        List<LoginUserInfo.Permission> userMyPermissions = BeanUtils.convert(myPermissions, LoginUserInfo.Permission.class);
        LoginUserInfo loginUserInfo = LoginUserInfo.builder()
                .userName(account.getUserName())
                .nickName(account.getNickName())
                .accountGroup(groupId)
                .role(role)
                .permissions(userMyPermissions)
                .build();

        Roles roleType = Roles.parse(role);
        //企业账户 或员工账户
        if (roleType == Roles.ENTERPRISE || roleType == Roles.EMPLOYEE) {
            Enterprise enterprise = enterpriseMapper.selectOne(Enterprise.builder()
                    .accountGroupId(groupId).build());
            loginUserInfo.setEnterpriseId(enterprise.getId());
            //员工账户
            if (roleType == Roles.EMPLOYEE) {
                Employee employee = employeeMapper.selectOne(Employee.builder()
                        .bindAccount(account.getUserName())
                        .enterpriseId(enterprise.getId())
                        .build());
                loginUserInfo.setEmployeeId(employee.getId());
            }
        }


        //缓存用户登录信息
        redisClient.setEntity(Const.LOGIN_USER_INFO + account.getUserName(), loginUserInfo);
        return loginUserInfo;
    }

    /**
     * 缓存登录用户信息
     *
     * @param account 账号
     * @param groupId 账户组id
     */
    public void cacheLoginUserInfo(Account account, Integer groupId) throws BusinessException {
        LoginUserInfo loginUserInfo = redisClient.getEntity(Const.LOGIN_USER_INFO + account.getUserName());
        String role = null;
        //如果还未缓存用户登录信息时,需要从数据库获取用户角色
        if (loginUserInfo == null || StringUtils.isBlank(loginUserInfo.getRole())) {
            List<AccountRole> accountRoles = accountRoleMapper.selectList(
                    new EntityWrapper<>(AccountRole.builder().userName(account.getUserName()).build()));
            if (accountRoles != null && accountRoles.size() > 0) {
                role = accountRoles.get(0).getRoleName();
            }
        } else {
            role = loginUserInfo.getRole();
        }
        if (StringUtils.isBlank(role)) {
            throw new BusinessException("用户:" + account.getUserName() + "角色为空");
        }
        cacheLoginUserInfo(account, groupId, role);
    }
}
